# -*- coding: utf-8 -*-
import requests
import json
import time
import hashlib
import random

def fanyi(keyword):
    # 要访问的地址
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    ts = str(int(time.time() * 1000))  # r = "" + (new Date).getTime()

    salt = ts + str(random.randint(0, 9))  # i = r + parseInt(10 * Math.random(), 10)

    # 获取sign文本并进行MD5加密
    # sign: n.md5("fanyideskweb" + e + i + "@6f#X3=cCuncYssPsuRUE")
    text = "fanyideskweb" + keyword + salt + "@6f#X3=cCuncYssPsuRUE"
    m = hashlib.md5()
    m.update(bytes(text, encoding="utf8"))
    sign = m.hexdigest()

    # 定义请求的参数，并编码转换
    data = {'i': keyword,  # 要翻译的词
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': salt,
            'sign': sign,
            'ts': ts,
            'bv': 'e2a78ed30c66e16a857c5b6486a1d326',  # 浏览器版本的md5加密
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTlME',
            }


    # 定义请求头
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Connection': 'keep-alive',
        'Content-Length': str(len(data)),
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=-372601874@10.169.0.83; OUTFOX_SEARCH_USER_ID_NCOO=130641828.03418593; JSESSIONID=aaaScK3viWeE0grnnD5Ow; ___rl__test__cookies=1555742121898',
        'Host': 'fanyi.youdao.com',
        'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
        'X-Requested-With': 'XMLHttpRequest',
    }

    # 发送请求，爬取信息
    res = requests.post(url, data=data, headers=headers)

    # 解析结果
    str_json = res.content.decode('utf-8')
    myjson = json.loads(str_json)
    print(myjson['translateResult'][0][0]['tgt'])


if __name__ == '__main__':
    while True:
        keyword = input('(requests)请输入要翻译的词：')
        if keyword == 'q':
            break
        fanyi(keyword)